<?php
#注册插件
RegisterPlugin("acgMora", "ActivePlugin_acgMora");

function ActivePlugin_acgMora()
{
  Add_Filter_Plugin('Filter_Plugin_Admin_TopMenu', 'acgMora_AddMenu');
  // Add_Filter_Plugin('Filter_Plugin_ViewAuto_Begin', 'acgMora_Rewrite');
  Add_Filter_Plugin('Filter_Plugin_ViewPost_Template', 'acgMora_Main');
  Add_Filter_Plugin('Filter_Plugin_ViewList_Template', 'acgMora_Main');
  Add_Filter_Plugin('Filter_Plugin_ViewSearch_Template', 'acgMora_Main');
  Add_Filter_Plugin('Filter_Plugin_Zbp_BuildTemplate', 'acgMora_Gentemplate');
  // Add_Filter_Plugin('Filter_Plugin_Cmd_Ajax', 'acgMora_Ajax');
  Add_Filter_Plugin('Filter_Plugin_ViewComment_Template', 'acgMora_ViewCMT');
  Add_Filter_Plugin('Filter_Plugin_ViewList_Core', 'acgMora_canonical');
  // 临时
  Add_Filter_Plugin('Filter_Plugin_LargeData_Article', 'acgMora_Order');
  // 接口挂载 - 侧栏模块保存时防止 FileName 大小写变化
  Add_Filter_Plugin('Filter_Plugin_Module_Save', 'acgMora_KeepModFileName');
}

// // 接口函数 - 侧栏模块保存时防止 FileName 大小写变化
function acgMora_KeepModFileName(&$mod)
{
  // 如果 $mod->FileName 为全小写
  if ("acgmora-tabs" === $mod->FileName) {
    // 将 $mod->FileName 恢复为原始值
    $mod->FileName = "acgMora-tabs";
  }
}

function acgMora_Order($s, $w, &$or, $l, $op)
{
  global $zbp;
  $order_get = GetVars('order', 'GET');
  if (empty($order_get) && $zbp->version > 172800) {
    $or = array('log_UpdateTime' => 'DESC');
  }
}
function acgMora_canonical()
{
  global $zbp;
  $fpargs = func_get_args();
  $url = $fpargs[7]->UrlRule;
  $zbp->fullcurrenturl = $url->Make();
}
function acgMora_AddMenu(&$m)
{
  global $zbp;
  $m[] = MakeTopMenu("root", '<b>主题配置</b>', $zbp->host . "zb_users/theme/acgMora/main.php", "", "acgMora");
}
function acgMora_ViewCMT(&$template)
{
  global $zbp;
  $type = $template->GetTags('type');
  // $comments = $template->GetTags('comments');
  $comment = $template->GetTags('comment');
  if ($comment->ParentID > 0) {
    $commentParent = $zbp->GetCommentByID($comment->ParentID);
    $template->SetTags('MizuPaN', array($comment->ParentID => $commentParent->Author->StaticName));
    $template->SetTemplate("comment-reply");
  }
}
function acgMora_Main(&$template)
{
  global $zbp;
  if ($tag = $template->GetTags('articles')) {
    foreach ($tag as $article) {
      acgMora_SetIMG($article);
    }
  } else if ($article = $template->GetTags('article')) {
    // if ($zbp->version < 172800) {
    //   $template->SetTags('UpdateTime', '');
    // } else {
    //   $template->SetTags('UpdateTime', acgMora_Time($article->UpdateTime));
    // }
    acgMora_SetIMG($article);
  }
}
function acgMora_SetIMG($post)
{
  // global $bloghost;
  if (!isset($post->FistImg)) {
    //$randnum=rand(1, 19);
    $randnum = $post->ID % 3 + 1;
    $pattern = "/<img[^>]+src=\"(?<url>[^\"]+\.(gif|jpg|png))\"[^>]*>/i";
    $content = $post->Content;
    $matchContent = array();
    preg_match($pattern, $content, $matchContent);
    if (isset($matchContent["url"])) {
      $temp = $matchContent["url"];
    } else {
      $temp = acgMora_Path("v-noimg", "host") . $randnum . ".webp";
    }
    $post->FistImg = $temp;
  }
}
// function acgMora_FoTweet($s, &$w, $or, $l, $op)
// {
//   $w[] = array('<>', 'log_Type', '1');
// }
function acgMora_Gentemplate(&$templates)
{
  global $zbp;
  $templates['n-tabs'] = $templates['m-tabs'];

  $zbp->LoadCategories();
  $tootID = $zbp->Config("acgMora")->tootID;
  if (isset($zbp->categories[$tootID])) {
    $tootCate = $zbp->categories[$tootID];
    $templates['n-tabs'] = str_replace("-tootURL-", $tootCate->Url, $templates['n-tabs']);
    CountCategory($zbp->categories[$tootID]);
    $zbp->categories[$tootID]->Save();
  } else {
    $templates['n-tabs'] = str_replace("-tootURL-", $zbp->host, $templates['n-tabs']);
    $templates['n-tabs'] = str_replace("is-toot", "is-toot is-hidden", $templates['n-tabs']);
  }

  // 由 m-usr-links 生成 n-usr-links，前台访问时使用 n-usr-links
  $templates['n-usr-links'] = "";
  if ($zbp->template->hasTemplate("m-usr-links")) {
    $templates['n-usr-links'] = $zbp->template->Output("m-usr-links");
  }
}
function acgMora_QR()
{
  global $zbp;
  $result = $zbp->host . 'zb_users/theme/acgMora/';
  $qrImgs = array();
  $qrImgs['wx'] = $result . 'usr/qr-wx.png';
  $qrImgs['qq'] = $result . 'usr/qr-qq.png';
  $qrImgs['ali'] = $result . 'usr/qr-ali.png';
  return $qrImgs;
}
function acgMora_Path($file, $t = 'path')
{
  global $zbp;
  $result = $zbp->$t . 'zb_users/theme/acgMora/';
  switch ($file) {
    case 'u-qr-wx':
      return $result . 'usr/qr-wx.png';
      break;
    case 'u-qr-qq':
      return $result . 'usr/qr-qq.png';
      break;
    case 'u-qr-ali':
      return $result . 'usr/qr-ali.png';
      break;
    case 'v-qr-def':
      return $result . 'var/qr-def.png';
      break;
    case 'u-fav':
      return $result . 'usr/favicon.ico';
      break;
    case 'v-fav':
      return $result . 'var/favicon.ico';
      break;
    case 'u-logo':
      return $result . 'usr/logo.png';
      break;
    case 'v-logo':
      return $result . 'var/logo.png';
      break;
      //---
    case 'v-noimg':
      return $result . 'var/noimg/';
      break;
    case 'usr':
      return $result . 'usr/';
      break;
    case 'var':
      return $result . 'var/';
      break;
    case 'main':
      return $result . 'main.php';
      break;
    default:
      return $result . $file;
  }
}
function acgMora_Time($ptime, $isStr = false)
{
  $ptime = $isStr ? strtotime($ptime) : $ptime;
  $etime = time() - $ptime;
  if ($etime < 1) return '刚刚';
  $interval = array(
    12 * 30 * 24 * 60 * 60  =>  '年前 (' . date('Y-m-d', $ptime) . ')',
    30 * 24 * 60 * 60       =>  '个月前 (' . date('m-d', $ptime) . ')',
    7 * 24 * 60 * 60        =>  '周前 (' . date('m-d', $ptime) . ')',
    24 * 60 * 60            =>  '天前',
    60 * 60                 =>  '小时前',
    60                      =>  '分钟前',
    1                       =>  '秒前'
  );
  foreach ($interval as $secs => $str) {
    $d = $etime / $secs;
    if ($d >= 1) {
      $r = round($d);
      return "{$r} {$str}";
    }
  };
}
function InstallPlugin_acgMora()
{
  global $zbp;
  if (!$zbp->HasConfig('acgMora')) {
    $zbp->Config('acgMora')->version = 1;
    $zbp->Config('acgMora')->keywords = "关键词";
    $zbp->Config('acgMora')->description = "站点描述";
    // $zbp->Config("acgMora")->tootCount = 0;
    $zbp->SaveConfig('acgMora');
  }
  $filesList = array("logo", "fav");
  foreach ($filesList as $key => $value) {
    $uFile = acgMora_Path("u-{$value}");
    $vFile = acgMora_Path("v-{$value}");
    if (!is_file($uFile)) {
      @mkdir(dirname($uFile));
      copy($vFile, $uFile);
    }
  }
  // 初始化打赏二维码
  $filesList = array("wx", "qq", "ali");
  $vFile = acgMora_Path("v-qr-def");
  foreach ($filesList as $key => $value) {
    $uFile = acgMora_Path("u-qr-{$value}");
    if (!is_file($uFile)) {
      @mkdir(dirname($uFile));
      copy($vFile, $uFile);
    }
  }
  ///
  $mod = $zbp->modulesbyfilename["tags"];
  $mod->Type = "div";
  $mod->Build();
  $mod->Save();
  ///
  $mod = new Module();
  $mod->Name = "[acgMora]附加导航";
  $mod->FileName = "acgMora-tabs";
  $mod->HtmlID = $mod->FileName;
  $mod->Source = "plugin_LinksManage";
  $mod->Content = '<li><a href="' . $zbp->host . 'zb_users/plugin/LinksManage/main.php?edit=acgMora-tabs" title="点击这里编辑">编辑此菜单</a></li>';
  $mod->Save();
  ///
  $zbp->option['ZC_SEARCH_TYPE'] = "list";
  $zbp->SaveOption();
  $zbp->BuildTemplate();
}
function UninstallPlugin_acgMora()
{
  global $zbp;
  $mod = $zbp->modulesbyfilename["tags"];
  $mod->Type = "ul";
  $mod->Save();
}
